import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import HomeView from '../views/HomeView.vue'
import WelcomeView from '../views/WelcomeView.vue'
import UserView from '../components/UserView.vue'
const routes = [
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  }, {
    path: '/login',
    name: 'login',
    component: Login
  }, {
    path: '/home',
    name: 'home',
    component: HomeView,
    redirect: '/welcome',
    children: [{
      path: '/welcome',
      name: 'welcome',
      component: WelcomeView
    }, {
      path: '/users',
      name: 'users',
      component: UserView
    }]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 路由导航控制
router.beforeEach((to, from, next) => {
  // to代表将要访问的路径
  // from代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
